package com.region.integral.business_user.obtain.dao.impl;

import java.util.List;

import org.springframework.stereotype.Component;

import com.region.integral.business_user.obtain.dao.IIntegralSellGoods;
import com.region.integral.business_user.pojo.BUIEntity;
import com.region.integral.business_user.xml.Regulation;
import com.region.integral.business_user.xml.dto.SellGoods;
import com.region.integral.common_user.obtain.vo.IntegralData;
import com.region.integral.exception.IntegralException;
import com.region.integral.hibernate.BaseHibernate;
import com.region.integral.util.BusinessUserLogUtil;
import com.region.integral.util.XMLRegulationUtil;
@Component("iIntegralSellGoods")
public class IntegralSellGoodsImpl extends BaseHibernate implements IIntegralSellGoods {

	@Override
	public void sellGoods(int userid, double price, IntegralData integralData)
			throws IntegralException {
		BUIEntity buiEntity = getBUIEntity(userid);
		if (buiEntity != null) {
			Regulation regulation = XMLRegulationUtil.unmarshaller2();
			List<SellGoods> sellGoods = regulation.getSellgoods();
			for (SellGoods sGoods : sellGoods) {
					if (sGoods.getBelow()!=0 && sGoods.getBetween()==0 && sGoods.getBelow() >= price) {
						int currIntegral = buiEntity.getCurrIntegral();
						int maxIntegral = buiEntity.getMaxIntegral();
						int totalIntegral = currIntegral+ sGoods.getIntegral();
						buiEntity.setCurrIntegral(totalIntegral);
						if (maxIntegral < totalIntegral) {
							buiEntity.setMaxIntegral(totalIntegral);
						}
						integralData.setSuccee(true);
						hibernateTemplate.update(buiEntity);
						hibernateTemplate.save(BusinessUserLogUtil.log(userid, sGoods.getIntegral(), "sellGoods"));
					}
					if (sGoods.getBetween()!=0 &&sGoods.getBelow()< price && sGoods.getBetween() >= price) {
						int currIntegral = buiEntity.getCurrIntegral();
						int maxIntegral = buiEntity.getMaxIntegral();
						int totalIntegral = currIntegral+ sGoods.getIntegral();
						buiEntity.setCurrIntegral(totalIntegral);
						if (maxIntegral < totalIntegral) {
							buiEntity.setMaxIntegral(totalIntegral);
						}
						integralData.setSuccee(true);
						hibernateTemplate.update(buiEntity);
						hibernateTemplate.save(BusinessUserLogUtil.log(userid, sGoods.getIntegral(), "sellGoods"));
					}
					if (sGoods.getOver()!=0 && sGoods.getOver() < price) {
						int currIntegral = buiEntity.getCurrIntegral();
						int maxIntegral = buiEntity.getMaxIntegral();
						int totalIntegral = currIntegral+ sGoods.getIntegral();
						buiEntity.setCurrIntegral(totalIntegral);
						if (maxIntegral < totalIntegral) {
							buiEntity.setMaxIntegral(totalIntegral);
						}
						integralData.setSuccee(true);
						hibernateTemplate.update(buiEntity);
						hibernateTemplate.save(BusinessUserLogUtil.log(userid, sGoods.getIntegral(), "sellGoods"));
					}
				}
			}
	}

}
